package logic

import (
	"common/biz"
	"core/models/entity"
	"fmt"
	"framework/msError"
	"framework/remote"
	"game/componet/room"
	"sync"
	"time"

	"golang.org/x/exp/rand"
)

type UnionManager struct {
	sync.RWMutex
	unionList map[int64]*Union
}

func NewUnionManager() *UnionManager {
	return &UnionManager{
		unionList: make(map[int64]*Union),
	}
}

func (u *UnionManager) GetUnion(unionId int64) *Union {
	u.Lock()
	defer u.Unlock()
	union, ok := u.unionList[unionId]
	if ok { //如果有这个id的联盟
		return union
	}
	union = NewUnion(unionId, u)
	//union.Init()
	u.unionList[unionId] = union
	return union
}

func (u *UnionManager) CreateNewRoomID() string {
	roomId := u.genRoomId()
	for _, v := range u.unionList {
		if v.RoomList[roomId] != nil { //如果有重复的id
			return u.CreateNewRoomID() //接着执行创建房间id
		}
	}
	return roomId
}

func (u *UnionManager) genRoomId() string {
	//gameServers := game.Conf.ServersConf.TypeServer["game"]
	rand.New(rand.NewSource(uint64(time.Now().UnixNano())))
	//房间号是6位数
	roomIdInt := rand.Int63n(999999)
	if roomIdInt < 100000 {
		roomIdInt += 100000
	}
	roomId := fmt.Sprintf("%d", roomIdInt)
	return roomId
}

func (u *UnionManager) GetRoomById(roomId string) *room.Room {
	for _, v := range u.unionList {
		r, ok := v.RoomList[roomId]
		if ok {
			return r
		}
	}
	return nil
}

func (u *UnionManager) JoinRoom(session *remote.Session, roomId string, data *entity.User) *msError.Error {
	for _, v := range u.unionList {
		r, ok := v.RoomList[roomId]
		if ok {
			return r.JoinRoom(session, data)
		}
	}
	return biz.RoomNotExist
}
